package com.z1.core.sequence;

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class SequenceUtil {

	/** The FieldPosition. */
	private static final FieldPosition HELPER_POSITION = new FieldPosition(0);
	/** This Format for format the data to special format. */
	private final static Format dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	/** This Format for format the number to special format. */
	private final static NumberFormat numberFormat = new DecimalFormat("0000");
	/** This int is the sequence number ,the default value is 0. */
	private static int seq = 0;
	private static final int MAX = 9999;
	
	private static String prevTime = ""; 

	/** * 时间格式生成序列 * @return String */
	public static synchronized String generateSequenceNo() {
		Calendar rightNow = Calendar.getInstance();
		StringBuffer sb = new StringBuffer();
		dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION);
		String curTime = sb.toString();
		if (!curTime.equals(prevTime)) {
			seq = 0;
		}
		numberFormat.format(seq, sb, HELPER_POSITION);
		if (seq == MAX) {
			seq = 0;
		}
		else {
			seq++;
		}
		prevTime = curTime;
		return sb.toString();
	}
	
	public static String[] CHARS = new String[] {
		"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
		"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", 
		"u", "v", "w", "x", "y", "z", "0", "1", "2", "3", 
		"4", "5", "6", "7", "8", "9", "A", "B", "C", "D", 
		"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", 
		"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", 
		"Y", "Z"
	};
	public static synchronized String generateUUID() {
		StringBuffer shortBuffer = new StringBuffer();  
	    String uuid = java.util.UUID.randomUUID().toString().replace("-", "");  
	    for (int i = 0; i < 8; i++) {  
	        String str = uuid.substring(i * 4, i * 4 + 4);  
	        int x = Integer.parseInt(str, 16);  
	        shortBuffer.append(CHARS[x % 0x3E]);  
	    }  
	    return shortBuffer.toString();
	}
	/** * 时间格式+UUID生成序列 * @return String */
	public static synchronized String generateUUIDSequenceNo() {
	    return generateSequenceNo() + "_" + generateUUID();
	}
	
	public static final String getShareCode() {
		return generateUUID();
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(generateSequenceNo());
		Thread.sleep(1000);
		System.out.println(generateSequenceNo());
		System.out.println(generateUUID());
		for (int i = 0; i < 10; i++) {
			System.out.println(generateUUIDSequenceNo());
		}
	}
}
